import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    appName: '分站管理系统',
    token: '',
    user: null,
    branchId: '',
    lastRoute: null,
    fullscreen: false
  },

  mutations: {
    setToken (state, token) {
      if (token) {
        state.token = token
        saveToken(token)
      }
    },

    setUser (state, user) {
      if (!user) return
      state.user = user
      saveUser(user)
    },
    setBranchId (state, id) {
      if (!id) return
      state.branchId = id
      saveBranchId(id)
    },
    deleteToken (state) {
      state.token = ''
    },
    deleteUser (state) {
      state.user = {}
    },
    deleteBranchId (state) {
      state.branchId = ''
    },
    setLastRoute (state, route) {
      state.lastRoute = route
    },

    toggleFullscreen (state, flag) {
      if (flag === undefined) {
        flag = !state.fullscreen
      }

      let result = false
      if (flag) {
        result = fullscreen()
      } else {
        result = exitFullscreen()
      }

      // 如果成功改变状态
      if (result) {
        state.fullscreen = flag
      }
    }
  }
})

export function fullscreen () {
  const el = document.documentElement
  const rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen

  if (rfs) {
    rfs.call(el)
    return true
  }

  return false
}

export function exitFullscreen () {
  const el = document
  const cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen

  if (cfs) {
    cfs.call(el)
    return true
  }

  return false
}

export function saveToken (token) {
  localStorage.removeItem('token')
  localStorage.setItem('token', token)
}
export function saveUser (user) {
  localStorage.removeItem('user')
  localStorage.setItem('user', user)
}
export function saveBranchId (id) {
  console.log('saveBranchId',id)
  localStorage.removeItem('branchId')
  localStorage.setItem('branchId', id)
}

export function getToken () {
  if (!store.state.token) {
    store.commit('setToken', localStorage.getItem('token'))
  }
  return store.state.token
}
export function getUser () {
  if (!store.state.user) {
    store.commit('setUser', localStorage.getItem('user'))
  }
  return store.state.user
}
export function getBranchId () {
  if (!store.state.branchId) {
    store.commit('setBranchId', localStorage.getItem('branchId'))
  }
  console.log(store.state.branchId)
  return store.state.branchId
}
export function logout () {
  store.commit('deleteToken')
  store.commit('deleteUser')
  store.commit('deleteBranchId')
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  localStorage.removeItem('branchId')
}

export default store
